import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:myapp/models/models.dart';

import '../../repositories/repositories.dart';

part 'user_profile_event.dart';
part 'user_profile_state.dart';

class UserProfileBloc extends Bloc<UserProfileEvent, UserProfileState> {
  final UserRepository userRepository;
  // final UserBloc userBloc;
  UserProfileBloc({required this.userRepository}) : super(UserProfileInitial()) {
    on<LoadUserProfileEvent>((event, emit) async {
      emit(UserProfileLoading());
      try{
        final user = await userRepository.getCorrentUser();
        emit(UserProfileLoaded(MyUser(userId: user.userId, email: user.email, name: user.name, profile: user.profile)));
      }catch (e){
        emit(UserProfileError(e));
      }
    });
    on<UpdateUserProfileEvent>((event, emit) async{
      emit(UserProfileLoading());
      try{
        // await userRepository.u
        var user = await userRepository.getCorrentUser();
        var updateUser=MyUser(userId: user.userId,email: event.user.email,name: event.user.name,profile: event.user.profile);
        await userRepository.setUserData(updateUser);
        emit(UserProfileLoaded(await userRepository.getCorrentUser()));
      }catch (e){
        emit(UserProfileError(e));
      }
    });
  }
}
